<template>
  <div style="display: flex">
    <div id="container"></div>
    <div style="display: flex; flex-direction: column; align-items: center">
      <el-button type="primary" class="but-class" @click="toggleLayer"
        >显示/隐藏图层</el-button
      >
      <el-button type="primary" class="but-class" @click="changeLayerOpcity"
        >随机修改图层透明度</el-button
      >
      <el-button type="primary" class="but-class" @click="heavyLoadLayer"
        >重载图层</el-button
      >
      <el-button type="primary" class="but-class" @click="toggleBLC"
        >显示/隐藏比例尺</el-button
      >
      <el-button type="primary" class="but-class" @click="toggleGJT"
        >显示/隐藏工具条</el-button
      >
      <el-button type="primary" class="but-class" @click="toggleFXP"
        >显示/隐藏工具条方向盘</el-button
      >
      <el-button type="primary" class="but-class" @click="toggleYY"
        >显示/隐藏鹰眼</el-button
      >
      <el-button type="primary" class="but-class" @click="getCurrentPosition"
        >当前位置</el-button
      >
      <el-button type="primary" class="but-class" @click="randomChangePosition"
        >随机更改位置</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
let map = null;
let layerGroup = null;
let trafficLayer = null;
let roadNetLayer = null;
let scale = null;
let toolBar = null;
let controlBar = null;
let overView = null;
let _AMap = null;
let MapType = null;
const marker = ref();
const lineArr = ref([
  [116.478935, 39.997761],
  [116.478939, 39.997825],
  [116.478912, 39.998549],
  [116.478912, 39.998549],
  [116.478998, 39.998555],
  [116.478998, 39.998555],
  [116.479282, 39.99856],
  [116.479658, 39.998528],
  [116.480151, 39.998453],
  [116.480784, 39.998302],
  [116.480784, 39.998302],
  [116.481149, 39.998184],
  [116.481573, 39.997997],
  [116.481863, 39.997846],
  [116.482072, 39.997718],
  [116.482362, 39.997718],
  [116.483633, 39.998935],
  [116.48367, 39.998968],
  [116.484648, 39.999861],
]);
onMounted(() => {
  AMapLoader.load({
    key: "906e92fdfc3d7f9421d2e8384a7a815b",
    resizeEnable: true,
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      "AMap.ToolBar",
      "AMap.Scale",
      "AMap.ControlBar",
      "AMap.HawkEye",
      "AMap.MapType",
    ], //需要使用的的插件列表
  })
    .then((AMap) => {
      // JSAPI2.0 使用覆盖物动画必须先加载动画插件
      AMap.plugin("AMap.MoveAnimation", function () {
        _AMap = AMap;
        map = new AMap.Map("container", {
          // 设置地图容器id
          viewMode: "3D", // 是否为3D地图模式
          zoom: 13, // 初始化地图级别
          center: [116.397428, 39.90923], // 初始化地图中心点位置
        });
        //小车配置
        marker.value = new AMap.Marker({
          map: map,
          position: [116.478935, 39.997761],
          icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
          offset: new AMap.Pixel(-13, -26),
        });
        // 绘制轨迹
        var polyline = new AMap.Polyline({
          map: map,
          path: lineArr.value,
          showDir: true,
          strokeColor: "#28F", //线颜色
          // strokeOpacity: 1,     //线透明度
          strokeWeight: 6, //线宽
          // strokeStyle: "solid"  //线样式
        });

        //移动后的轨迹
        var passedPolyline = new AMap.Polyline({
          map: map,
          strokeColor: "#AF5", //线颜色
          strokeWeight: 6, //线宽
        });

        marker.value.on("moving", function (e) {
          console.log("!!");
          passedPolyline.setPath(e.passedPath);
          map.setCenter(e.target.getPosition(), true);
        });

        map.setFitView();

        scale = new AMap.Scale({
          visible: true,
        });
        //  AMap.ToolBar比例尺插件。位于地图右下角，用户可控制其显示与隐藏
        toolBar = new AMap.ToolBar({
          visible: true,
          position: {
            top: "110px",
            right: "40px",
          },
        });
        // ControlBar 组合了旋转、倾斜、复位在内的地图控件。
        controlBar = new AMap.ControlBar({
          visible: true,
          position: {
            top: "10px",
            right: "10px",
          },
        });
        // HawkEye 鹰眼控件，用于显示缩略地图，显示于地图右下角，可以随主图的视口变化而变化，也可以配置成固定位置实现类似于南海附图的效果。
        overView = new AMap.HawkEye({
          visible: true,
        });
        // MapType 地图类型切换插件。用户通过该插件进行地图切换。
        MapType = new AMap.MapType({
          visible: true,
          position: {
            top: "200px",
            right: "10px",
          },
        });
        // addControl 添加控件。参数可以是插件列表中的任何插件对象
        map.addControl(scale);
        map.addControl(toolBar);
        map.addControl(controlBar);
        map.addControl(overView);
        map.addControl(MapType);

        map.on("click", mapClick);
        map.on("dblclick", mapDbClick);
        // TileLayer 切片图层类，该类为基础类
        // RoadNet 路网图层，展示道路信息. Traffic实时交通图层类，继承自TileLayer
        roadNetLayer = new AMap.TileLayer.RoadNet({
          zIndex: 10,
        });
        trafficLayer = new AMap.TileLayer.Traffic({
          zIndex: 11,
        });
        // LayerGroup 对实例集合做批量操作
        layerGroup = new AMap.LayerGroup([trafficLayer, roadNetLayer]);
        // 添加到地图上面
        layerGroup.setMap(map);
      });
    })
    .catch((e) => {
      console.log(e);
    });
});

const mapClick = (e) => {
  console.log(
    "%c [  ]-139",
    "font-size:13px; background:pink; color:#bf2c9f;",
    "进入mapClick"
  );
  changePosition(e.lnglat.lng, e.lnglat.lat);
};
const mapDbClick = () => {};

let layerFlag = true;
const toggleLayer = () => {
  console.log(layerGroup, "显示/隐藏图层");
  if (layerFlag) {
    layerGroup.hide();
  } else {
    layerGroup.show();
  }
  layerFlag = !layerFlag;
};
const changeLayerOpcity = () => {
  layerGroup.setOptions({ opacity: Math.random() });
};
const heavyLoadLayer = () => {
  layerGroup.reload();
};

let blcFlag = true;
const toggleBLC = () => {
  if (blcFlag) {
    scale.hide();
  } else {
    scale.show();
  }
  blcFlag = !blcFlag;
};
let gjtFlag = true;
const toggleGJT = () => {
  if (gjtFlag) {
    toolBar.hide();
  } else {
    toolBar.show();
  }
  gjtFlag = !gjtFlag;
};
let fxpFlag = true;
const toggleFXP = () => {
  if (fxpFlag) {
    controlBar.hide();
  } else {
    controlBar.show();
  }
  fxpFlag = !fxpFlag;
};
let yyFlag = true;
const toggleYY = () => {
  if (yyFlag) {
    overView.hide();
  } else {
    overView.show();
  }
  yyFlag = !yyFlag;
};

const getCurrentPosition = () => {
  _AMap.plugin("AMap.Geolocation", function () {
    let geolocation = new _AMap.Geolocation({
      enableHighAccuracy: true, //是否使用高精度定位，默认:true
      timeout: 100000, //超过10秒后停止定位，默认：5s
      position: "RB", //定位按钮的停靠位置
      offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
      zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
    });
    console.log("定位成功");
    map.addControl(geolocation);
    geolocation.getCurrentPosition(function (status, result) {
      if (status == "complete") {
        // 标记位置
        changePosition(result.position.lng, result.position.lat);
      } else {
        console.log(result, "error");
      }
    });
  });
};

const changePosition = (lng, lat, scale = 10) => {
  map.setCenter([lng, lat]);
  map.setZoom(scale);
  marker = new _AMap.Marker({
    icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
    position: [lng, lat],
    offset: new _AMap.Pixel(-13, -30),
    content: `<div class="marker">
                     <span>经度:${lng.toFixed(2)}</span>
                     <br/>
                     <span>纬度:${lat.toFixed(2)}</span>
                </div>`,
  });
  marker.setMap(map);
};

const randomChangePosition = () => {
  changePosition(
    Math.random() * (135 - 73.5) + 73.5,
    Math.random() * (53.6 - 18) + 18,
    7
  );
};
onUnmounted(() => {
  map?.destroy();
});
</script>

<style lang="scss">
#container {
  width: 900px;
  height: 700px;
}
.amap-marker .marker {
  width: 100px;
  padding: 3px;
  color: #fff;
  font-size: 12px;
  background-color: #000;
}
.but-class {
  width: 200px;
  margin: 10px 0 0 0;
}
</style>
